import * as React from 'react';
import {Link} from 'react-router-dom';
import pathToRegexp from 'path-to-regexp';
import {Layout, Menu, Icon} from 'antd';
import {urlToList} from '../../util/tool'
import './index.less';

const {Sider} = Layout;
const {SubMenu} = Menu;


export default class SiderMenu extends React.PureComponent<any> {
    public flatMenuKeys: any;

    public state: any;

    constructor(props: any) {
        super(props);

        this.state = {
            openKeys: this.getDefaultCollapsedSubMenus(props)
        }
        this.flatMenuKeys = this.getFlatMenuKeys(props.menuData);
    }

    public getDefaultCollapsedSubMenus = (props: any) => {
        const pathname = window.location.pathname;

        if (!this.flatMenuKeys) {
            this.flatMenuKeys = this.getFlatMenuKeys(props.menuData);
        }

        return this.getMenuMatchKeys(this.flatMenuKeys, urlToList(pathname));
    }
// 获取图标
    public getIcon = (icon: string) => {
        if (typeof icon === 'string') {
            if (icon.indexOf('http') === 0) {
                return <img src={icon}
                            alt="icon"
                            className={`icon sider-menu-item-img`}
                />;
            }
            return <Icon className={`icon sider-menu-item-img`} type={icon}/>;
        }

        return icon;
    }
    // 转化路径
    public conversionPath = (path: string): string => {
        if (path && path.indexOf('http') === 0) {
            return path;
        } else {
            return `/${path || ''}`.replace(/\/+/g, '/');
        }
    };
    /**
     * 判断是否是http链接.返回 Link 或 a
     * Judge whether it is http link.return a or Link
     * @memberof SiderMenu
     */
    public getMenuItemPath = (item: any) => {
        const itemPath = this.conversionPath(item.path);
        const icon = this.getIcon(item.icon);
        const {target, name} = item;
        // Is it a http link
        if (/^https?:\/\//.test(itemPath)) {
            return (
                <a href={itemPath} target={target}>
                    {icon}
                    <span>{name}</span>
                </a>
            );
        }
        return (
            <Link
                to={itemPath}
                target={target}
                replace={itemPath === window.location.pathname}
                onClick={
                    () => {
                        console.log(111);
                    }}
            >
                {icon}
                <span>{name}</span>
            </Link>
        );
    };
    /**
     * 获得菜单子节点
     * @memberof SiderMenu
     */
    public getNavMenuItems = (menusData: any) => {
        if (!menusData) {
            return [];
        }
        return menusData
            .filter((item: any) => item.name && !item.hideInMenu)
            .map((item: any) => {
                return this.getSubMenuOrItem(item);
            })
            .filter((item: any) => item);
    };
    public getSubMenuOrItem = (item: any) => {
        if (item.children && item.children.some((child: any) => child.name)) {
            const childrenItems = this.getNavMenuItems(item.children);
            // 当无子菜单时就不展示菜单
            if (childrenItems && childrenItems.length > 0) {
                return (
                    <SubMenu
                        title={
                            item.icon ? (
                                <span>
                  {this.getIcon(item.icon)}
                                    <span>{item.name}</span>
                </span>
                            ) : (
                                item.name
                            )
                        }
                        key={item.path}
                    >
                        {childrenItems}
                    </SubMenu>
                );
            }
            return null;
        } else {
            return <Menu.Item key={item.path}>{this.getMenuItemPath(item)}</Menu.Item>;
        }
    }
    public isMainMenu = (key: string) => {
        const {menuData} = this.props;
        return menuData.some((item: any) => key && (item.key === key || item.path === key));
    };
    public handleOpenChange = (openKeys: any[]) => {
        const lastOpenKey = openKeys[openKeys.length - 1];
        const moreThanOne = openKeys.filter(openKey => this.isMainMenu(openKey)).length > 1;
        this.setState({
            openKeys: moreThanOne ? [lastOpenKey] : [...openKeys],
        });
    };
    public getMenuMatchKeys = (flatMenuKeys: any, paths: string[]) => {
        return paths.reduce(
            (matchKeys, path) =>
                matchKeys.concat(flatMenuKeys.filter((item: any) => pathToRegexp(item).test(path))),
            []
        );
    }

    public getFlatMenuKeys = (menu: any[]): any[] => {
        return menu.reduce((keys, item) => {
            keys.push(item.path);
            if (item.children) {
                return keys.concat(this.getFlatMenuKeys(item.children));
            }
            return keys;
        }, []);
    }
    public getSelectedMenuKeys = () => {
        const pathname = window.location.pathname;
        return this.getMenuMatchKeys(this.flatMenuKeys, urlToList(pathname));
    };

    public render() {
        const {collapsed, onCollapse, menuData} = this.props;

        const {openKeys} = this.state;

        let selectedKeys: any[] = this.getSelectedMenuKeys();

        if (!selectedKeys.length) {
            selectedKeys = [openKeys[openKeys.length - 1]];
        }
        return (
            <Sider
                trigger={null}
                collapsible={true}
                collapsed={collapsed}
                breakpoint="lg"
                onCollapse={onCollapse}
                width={256}
                className="global-sider"
            >
                <div className="logo" key="logo">
                    <Link to="/">
                        <h1>{collapsed ? 'cs' : 'chuans'}</h1>
                    </Link>
                </div>
                <Menu
                    key="Menu"
                    theme="dark"
                    mode="inline"
                    openKeys={openKeys}
                    onOpenChange={this.handleOpenChange}
                    selectedKeys={selectedKeys}
                    style={{padding: '16px 0', width: '100%'}}
                >
                    {this.getNavMenuItems(menuData)}
                </Menu>
            </Sider>
        );
    }
}
